package com.snmp.smn.agent;

import java.io.File;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.io.FileUtils;

import com.snmp.smn.pdu.PDUFactory;
import com.snmp.smn.utils.Utilities;

public class FileCopier extends Thread {
	
	private Socket socket;
	
	private String managerIP;
	
	private int managerPort;

	private String altManagerIP;

	private int altManagerPort;

	public FileCopier(Socket socket, String managerIP, int managerPort, String altManagerIP, int altManagerPort) {
		this.socket = socket;
		this.managerIP = managerIP;
		this.managerPort = managerPort;
		this.altManagerIP = altManagerIP;
		this.altManagerPort = altManagerPort;
	}
	
	public void run() {
		try {
			byte[] b = new byte[1024];
			socket.getInputStream().read(b);
			socket.close();
			
			String fileName = new String(b).trim();
			readFile(fileName);
		} catch (Exception e) {
			
		}
	}
	
	public void readFile(String fileName) throws Exception {
		Socket socket = new Socket(managerIP, managerPort);
		OutputStream os = socket.getOutputStream();
		os.write(PDUFactory.createFileInfoRequestPDU(fileName));
		
		byte[] b = new byte[1024];
		socket.getInputStream().read(b);
		socket.close();
		String data = Utilities.getMessageData(new String(b).trim());
		
		if (Utilities.isErrorMessage(data)) {
			Utilities.log("Cannot copy file : " + fileName + ". " + data);
		} else {
			int size = Integer.parseInt(data);
			b = new byte[size];
			for (int i=0; i<size; i++) {
				try {
					socket = new Socket(managerIP, managerPort);
					os = socket.getOutputStream();
					os.write(PDUFactory.createFileContentRequestPDU(fileName, i));
					
					byte[] res = new byte[1024];
					socket.getInputStream().read(res);
					socket.close();
					
					String response = new String(res).trim();
					char c = response.length() == 2 ? ' ' : response.charAt(response.length() - 1);
					b[i] = (byte) c;
				} catch (Exception e) {
					managerIP = altManagerIP;
					managerPort = altManagerPort;
					i--;
				}
			}
			FileUtils.writeByteArrayToFile(new File(fileName), b);
		}
	}
}